package com.qiyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiyu.common.ServiceException;
import com.qiyu.dao.HomeSettingMapper;
import com.qiyu.entity.HomeSetting;
import com.qiyu.model.request.backend.HomeSettingReq;
import com.qiyu.service.HomeSettingService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 首页设置（二维码、电话等)
 *
 * @author zhangweiwei
 * @date 2020-07-30
 */
@Service
public class HomeSettingServiceImpl extends ServiceImpl<HomeSettingMapper, HomeSetting> implements HomeSettingService {
    @Override
    public HomeSetting saveSetting(HomeSettingReq req) {
        if(StringUtils.isEmpty(req.getHandler())){
            throw new ServiceException("请传入handler");
        }
        HomeSetting homeSetting = new HomeSetting();

        switch (req.getHandler()){
            case "query":
                homeSetting = this.query(req);
                break;
            case "update":
                homeSetting = this.update(req);
                break;
            default:
                throw new ServiceException("handler 传值不正确，请传入 'query' 或者 'update'");
        }

        return homeSetting;
    }

    private HomeSetting query(HomeSettingReq req){
        QueryWrapper<HomeSetting> wrapper = new QueryWrapper<>();
        wrapper.lambda().isNotNull(HomeSetting::getId);
        HomeSetting homeSetting =  this.getOne(wrapper);
        return  homeSetting;
    }
    private HomeSetting update(HomeSettingReq req){
        HomeSetting homeSetting = this.query(req);
        if(homeSetting == null){
            homeSetting = new HomeSetting();

        }
        BeanUtils.copyProperties(req,homeSetting);
        saveOrUpdate(homeSetting);
        return this.query(req);

    }
    


}